# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通达信历史数据
"""
import datetime
import numpy as np
from typing import List
import sys
sys.path.append("../../")
from bangth_utils.mysql_database import MySQL
from bangth_utils.future.futureklinedata import CFutureKlineItem, CFutureKlineStore
from bangth_utils.user_logbook import user_log as logger


def convert_date_to_date_int(dt):
    t = dt.year * 10000 + dt.month * 100 + dt.day
    return t


def convert_time_to_time_int(dt):
    t = dt.hour * 10000 + dt.minute * 100 + dt.second
    return t


class FutureHqData:
    @staticmethod
    def get_future_codes(interval):
        """返回code_list"""
        mysql = MySQL("hqdb")
        sql = "SELECT code from tbl_future_kline_min{} group by code".format(interval)
        datas = mysql.query(sql)
        items = list()
        for item in datas:
            items.append(item[0])
        return items

    @staticmethod
    def get_future_hq(interval, code):
        dtype = np.dtype([('date', '<u4'), ('time', '<u4'), ('open', '<u4'),
                          ('close', '<u4'), ('high', '<u4'), ('low', '<u4'),
                          ('limit_up', '<u4'), ('limit_down', '<u4'), ('basis_spread', '<i4'),
                          ('open_interest', '<u4'), ('volume', '<u4'), ('total_turnover', '<u8'),
                          ('trade_date', '<u4')])

        mysql = MySQL("hqdb")
        sql = "SELECT code,datetime,open,close,high,low,volume,close_oi from tbl_future_kline_min{} where code='{}'" \
              " ORDER BY datetime desc".format(interval, code)
        datas = mysql.query(sql)
        items = list()
        logger.info("parse begin...")
        for item in reversed(datas):
            ft = CFutureKlineItem()
            ft.code = str(item[0])
            ft.date = convert_date_to_date_int(item[1])
            ft.time = convert_time_to_time_int(item[1])
            ft.open = float(item[2]) * 10000
            ft.close = float(item[3]) * 10000
            ft.high = float(item[4]) * 10000
            ft.low = float(item[5]) * 10000
            ft.volume = float(item[6])
            ft.limit_down = 0.0
            ft.limit_up = 0.0
            items.append((ft.date, ft.time, ft.open, ft.close, ft.high, ft.low,
                                   0, 0, 0, 0, ft.volume, 0, ft.date))

        logger.info("parse end.")
        result = np.array(items, dtype=dtype)
        logger.info("parse end..")
        return result


if __name__ == '__main__':
    a = dict()
    a.keys()
